import { LANG, TAGS_VIEW } from '@/constant'
import { getItem, setItem } from '@/utils/storage'
import router from '@/router'
import { ElMessage } from 'element-plus'

export default {
  namespaced: true,
  state: () => ({
    sidebarOpened: true,
    language: getItem(LANG) || 'zh',
    tagsViewList: getItem(TAGS_VIEW) || []
  }),
  mutations: {
    triggerSidebarOpened(state) {
      state.sidebarOpened = !state.sidebarOpened
    },
    /**
     * 设置国际化
     */
    setLanguage(state, lang) {
      setItem(LANG, lang)
      state.language = lang
    },
    /**
     * 初始化 tagsList
     */
    initTagsViewList(state) {
      state.tagsViewList = []
    },
    /**
     * 添加 tags
     */
    addTagsViewList(state, tag) {
      const isFind = state.tagsViewList.find(item => {
        return item.path === tag.path
      })
      // 处理重复
      if (!isFind) {
        state.tagsViewList.push(tag)
        setItem(TAGS_VIEW, state.tagsViewList)
      }
    },
    /**
     * 为指定的 tag 修改 title
     */
    changeTagsView(state, { index, tag }) {
      state.tagsViewList[index] = tag
      setItem(TAGS_VIEW, state.tagsViewList)
    },
    /**
     * 删除 tag
     * @param {type: 'other'||'right'||'index', index: index} payload
     */
    removeTagsView(state, payload) {
      //console.log('state', state)
      //console.log('payload', payload)
      //console.log('TagList', state.tagsViewList)
      //console.log('i_index', payload.index)

      if (payload.type === 'index') {
        state.tagsViewList.splice(payload.index, 1)
        // return
      } else if (payload.type === 'other') {
        state.tagsViewList.splice(
          payload.index + 1,
          state.tagsViewList.length - payload.index + 1
        )
        state.tagsViewList.splice(0, payload.index)
      } else if (payload.type === 'right') {
        state.tagsViewList.splice(
          payload.index + 1,
          state.tagsViewList.length - payload.index + 1
        )
      }
      setItem(TAGS_VIEW, state.tagsViewList)
    },

    removeTagsView2(state, payload) {
      //console.log('TagList', state.tagsViewList)
      // //console.log('i_index', payload.index)
      //console.log('state.tagsViewList.length', state.tagsViewList.length)
      //console.log('state.tagsViewList[1]', state.tagsViewList[1])

      if (state.tagsViewList.length === 1) {
        //console.log('至少打开一个页签')
        ElMessage.warning('至少打开一个页签') // 提示错误消息
      } else {
        state.tagsViewList.splice(payload.index, 1)
        if (payload.index !== 0) {
          router.push(state.tagsViewList[payload.index - 1])
        } else if (payload.index === 0 && state.tagsViewList.length !== 0) {
          router.push(state.tagsViewList[payload.index])
        } else if (payload.index === 0 && state.tagsViewList.length === 0) {
          router.push('/profile')
        }
        setItem(TAGS_VIEW, state.tagsViewList)
      }
    }
  },
  actions: {}
}
